#include <string>
#include <iostream>
#include "comm.hpp"
#include "Log.hpp"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <netinet/in.h>
#include<arpa/inet.h>

void Usage(std::string proc)
{
    std::cout << "Usage: \n\t" << proc << " server_ip server_port" << std::endl;
}

int main(int args, char *argv[])
{
    if (args != 3)
    {
        Usage(argv[0]);
        exit(Usage_err);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        exit(Socket_error);
    }
    std::cout<<"create socket success:"<< sock <<std::endl;

    //不需要bind，由OS随机
    //填充server信息
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());

    while(true)
    {
        std::string inbuffer;
        std::cout<<"Plead Enter# ";
        std::getline(std::cin,inbuffer);
        ssize_t n=sendto(sock,inbuffer.c_str(),sizeof(inbuffer),0,(struct sockaddr*)&server,sizeof(server));

        //发送成功
        if(n>0)
        {
            //收消息
            char buff[1024];
            struct sockaddr_in tmp;
            socklen_t len=sizeof(tmp);
            int m=recvfrom(sock,buff,sizeof(buff)-1,0,(struct sockaddr*)&tmp,&len);
            if(m>0)
            {
                buff[1024]=0;
                std::cout<<"server echo# "<<buff<<std::endl;           
            }
            else
                break;
        }
        else 
            break;
    }
    close (sock);
    return 0;
}